// store/modules/manager.js
import { getManagerBasicInfo } from "@/api/login";
import WebSocketService from "@/util/manager_api/websocket-serve";
export default {
  namespaced: true,
  state: {
    token: '',
    userInfo: {},
    ws: WebSocketService,
    onlineUsersMap: {},
    allChatRecords: {},
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem('managerToken', token);
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = { ...state.userInfo, ...userInfo };
    },
    CLEAR_STATE(state) {
      state.token = null;
      state.userInfo = {};
      localStorage.removeItem('managerToken');
      if (state.ws) {
        state.ws.close();
        state.ws = WebSocketService; // 重置为初始实例
      }
      state.onlineUsersMap = {};
      state.allChatRecords = {};
    },
    SET_WS(state, ws) {
      state.ws = ws;
    },
    SET_ONLINE_USERS(state, onlineUsersMap) {
      state.onlineUsersMap = onlineUsersMap;
    },
    SET_CHAT_RECORDS(state, { contactUserId, records }) {
      state.allChatRecords[contactUserId] = records;
    }
  },
  actions: {
    // 登录方法
    login({ commit }, { token }) {
      commit('SET_TOKEN', token);
    },

    async initAuth({ commit, state }) {
      const token = localStorage.getItem("managerToken");
      if (token) {
        commit("SET_TOKEN", token);
        try {
          const response = await getManagerBasicInfo();
          commit("SET_USER_INFO", response.data.data);
        } catch (error) {
          commit("CLEAR_STATE");
        }
      }
    },

    // 获取管理员信息
    async fetchManagerInfo({ state, commit }) {
      // 检查是否已有缓存且有效
      if (state.userInfo && state.userInfo.userId && typeof state.userInfo === 'object') {
        return state.userInfo;
      }

      if (!state.token) {
        console.log('Token 不存在，不发送验证请求');
        return false;
      }
      try {
        const response = await getManagerBasicInfo();
        if (response.data.code === 201 && response.data.data.userId) {
          commit('SET_USER_INFO', response.data.data);
          return response.data.data;
        } else {
          throw new Error(response.data.message || '用户信息获取失败');
        }
      } catch (error) {
        commit('CLEAR_STATE');
        return false;
      }
    },
    
    // 初始化WebSocket连接（仅在登录成功后调用）
    initWebSocket({ state, commit }) {
      return new Promise((resolve, reject) => {
        console.log('准备初始化WebSocket:', 'token存在:', !!state.token);
        if (!state.token) {
          console.error('Token不存在，无法初始化WebSocket');
          reject(new Error('Token不存在，无法初始化WebSocket'));
          return;
        }

        try {
          // 如果已有连接，先关闭
          if (state.ws && state.ws.isConnected) {
            state.ws.close();
          }

          // 初始化WebSocket连接
          WebSocketService.init(state.token);
          commit('SET_WS', WebSocketService);
          
          // 监听连接成功事件
          const openHandler = () => {
            console.log('WebSocket连接成功');
            WebSocketService.off('ws-open', openHandler);
            resolve();
          };
          
          // 监听连接错误事件
          const errorHandler = (error) => {
            console.error('WebSocket连接失败:', error);
            WebSocketService.off('ws-error', errorHandler);
            reject(error);
          };
          
          WebSocketService.on('ws-open', openHandler);
          WebSocketService.on('ws-error', errorHandler);

          // 消息处理
          WebSocketService.on('ws-message', (data) => {
            try {
              const eventStr = typeof data === 'string'
                ? data
                : (() => {
                  if (data && typeof data === 'object' && !Array.isArray(data) && !(data instanceof HTMLElement)) {
                    try {
                      return JSON.stringify(data);
                    } catch (stringifyError) {
                      console.warn('数据包含循环引用，无法序列化:', stringifyError);
                      return String(data);
                    }
                  }
                  return String(data);
                })();
              const fixedData = eventStr
                .replace(/([{,]\s*)(\d+)(\s*:)/g, '$1"$2"$3')
                .replace(/,\s*([}\]])/g, '$1');
              const rawData = JSON.parse(fixedData);
              console.log('聊天消息', rawData)
              
              if (rawData.messageType === 'CHAT_RECORD') {
                rawData.message.forEach(contactRecord => {
                  if (contactRecord && contactRecord.contactUserId && Array.isArray(contactRecord.messageSendRespList)) {
                    const formattedMessage = contactRecord.messageSendRespList.map(msg => ({
                      createdAt: msg.createdAt,
                      fromUserId: msg.fromUserId,
                      message: msg.message,
                      messageType: msg.messageType,
                      toUserId: msg.toUserId,
                      online: state.onlineUsersMap[msg.fromUserId] !== undefined
                    })).sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
                    commit('SET_CHAT_RECORDS', { contactUserId: contactRecord.contactUserId, records: formattedMessage });
                  }
                });
              } else if (rawData.messageType === 'TEXT') {
                const newMessage = {
                  createdAt: rawData.createdAt,
                  fromUserId: rawData.fromUserId,
                  message: rawData.message,
                  messageType: rawData.messageType,
                  toUserId: rawData.toUserId,
                  online: rawData.online !== undefined ? rawData.online : false
                };
                if (newMessage.toUserId === state.userInfo.userId) {
                  commit('SET_CHAT_RECORDS', {
                    contactUserId: newMessage.fromUserId,
                    records: [
                      ...(state.allChatRecords[newMessage.fromUserId] || []),
                      newMessage
                    ]
                  })
                }
              } else if (rawData.messageType === 'ONLINE_USERS') {
                if (typeof rawData.message === 'object' && rawData.message != null) {
                  commit('SET_ONLINE_USERS', rawData.message);
                } else {
                  console.warn('ONLINE_USERS消息格式错误:', rawData.message);
                  commit('SET_ONLINE_USERS', {});
                }
              }
            } catch (err) {
              console.error('解析消息失败:', err);
            }
          })
        } catch (error) {
          console.error('WebSocket初始化失败:', error);
          reject(error);
        }
      });
    },
  },

  getters: {
    token(state) {
      return state.token;
    },
    userInfo(state) {
      return state.userInfo;
    },
    // 获取用户类型
    userType(state) {
      return state.userInfo.managerType || '';
    },
    isSuperAdmin(state) {
      return state.userInfo.managerType === 'SUPER';
    },
    ws(state) {
      return state.ws;
    },
    onlineUsersMap(state) {
      return state.onlineUsersMap;
    },
    allChatRecords(state) {
      return state.allChatRecords;
    }

  }
};